<?php
namespace common\components;

use Yii;

use common\models;
use common\models\Systemconfig;

use yii\helpers\FileHelper;
use common\components\Helpercurl;


/**
 * 自定义助手,建议系统各个实现的功能放在此目录下面
 * lifei
 */
class Myhelpers {
	
	/**
	 * form上传文件到又拍云
	 */
    public static function upload2upy($file){
        //上传到又拍云
        $upyun_config = Systemconfig::getConfigValue('upyun');
        if (empty($upyun_config)) {
            echo '又拍云配制为空';exit;
        }
        require_once dirname(__DIR__).'/components/upyun/upyun.class.php';
        $upyun = new \UpYun($upyun_config['upyun_bucket'], $upyun_config['upyun_username'], $upyun_config['upyun_password']);

        //$fh = fopen('umeditor/php/upload/20150513/14315295316921.png', 'rb');
        //$fh = file_get_contents($file['tmp_name']);


        $type = getFileType($file['type']);

        $file_name = md5($file['tmp_name']);
        $url = '/'.$upyun_config['upyun_upload_dir'].date('/Y/m/').$file_name.$type;
        $rsp = $upyun->writeFile($url, file_get_contents($file['tmp_name']),true);   // 上传图片，自动创建目录

        return $upyun_config['upyun_http_domain'].$url;
    }


    /**
     *  @DESC 非表单上传至又拍云
     *  file_content_type 1链接或者文件名   2文件流
     */
    public static function nFormUpload2upy ($fileUrl, $type = '.jpg', $file_content_type = 1)
    {
        //上传到又拍云
        $upyun_config = Systemconfig::getConfigValue('upyun');
        if (empty($upyun_config)) {
            echo '又拍云配制为空';exit;
        }
        require_once dirname(__DIR__).'/components/upyun/upyun.class.php';
        $upyun = new \UpYun($upyun_config['upyun_bucket'], $upyun_config['upyun_username'], $upyun_config['upyun_password']);

        $file_name=md5($fileUrl.time());
        $url = '/'.$upyun_config['upyun_upload_dir'].date('/Y/m/').$file_name.$type;
        //链接或者文件名
        if ($file_content_type == 1) {
            $rsp = $upyun->writeFile($url, file_get_contents($fileUrl),true);
        }
        //文件流
        if ($file_content_type == 2) {
            $rsp = $upyun->writeFile($url, $fileUrl,true);
        }       
        return $upyun_config['upyun_http_domain'].$url;
    }


    /**
     *  @description 各业务类型ID
     *  @$business_type 各业务类型ID
     */
    public static function getOrderID($type)
    {
        if(empty($type) || !in_array($type, array(10, 11, 12,  30, 40, 50, 60, 70, 80, 90))) return false;

        //mysql 表锁
        $db = Yii::$app->db;
        $sql = "REPLACE INTO id_{$type}(stub) VALUES(1)";
        $flag = $db->createCommand($sql)->execute();
        $id = $db->getLastInsertID();
        //组合业务id
        $id_format = sprintf("%06d", $id);
        $order_id = $type . date('ymd') . $id_format;

        return $order_id;
    }

    /**
     * client ip
     **/
    public static function getClientIP()
    {
        if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $ip = getenv('REMOTE_ADDR');
        } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
    }

    /**
     * @desc 单对象转数组
     */
    public static function class_to_array($class){
        $rs=array();
        if(!empty($class))
            $rs=$class->attributes;
        return $rs;

    }

    /**
     * 发送模板短信 G::sendSms('1865811027', array ('content' => 'xxxx'));
     * @param to 手机号码集合,用英文逗号分开
     * @param $common Array 元素说明
     * =====================================================================================================================================
     *   content 内容
     *   tempId 模板Id
     *   vars 要替换的数据
     * =====================================================================================================================================
     * @return obj 返回的是对象
     */
    public static function sendSms ($to, $common)
    {
        //判断设定的短信通道，在系统设置里配置，根据该值判断选择不同的短信通道
        $smsType = trim(Systemconfig::getValue('sms_type'));

        //sendcloud
        if ($smsType == 'sc') {
            //获取系统配置
            $sms_config = Systemconfig::getConfigValue('sc_sms');
            $url = $sms_config['sc_sms_send_url'];

            $param = array(
                'smsUser' => $sms_config['sc_sms_user'],
                'templateId' => $common['templateId'],
                'msgType' => '0',
                'phone' => $to,
                'vars' => $common['vars'],
            );

            $sParamStr = "";
            ksort($param);
            foreach ($param as $sKey => $sValue) {
                $sParamStr .= $sKey . '=' . $sValue . '&';
            }

            $sParamStr = trim($sParamStr, '&');
            $smskey = $sms_config['sc_sms_key'];
            $sSignature = md5($smskey."&".$sParamStr."&".$smskey);

            $param = array(
                'smsUser' => $sms_config['sc_sms_user'],
                'templateId' => $common['templateId'],
                'msgType' => '0',
                'phone' => $to,
                'vars' => $common['vars'],
                'signature' => $sSignature
            );

            $data = http_build_query($param);

            $options = array(
                'http' => array(
                    'method' => 'POST',
                    'header' => 'Content-Type:application/x-www-form-urlencoded',
                    'content' => $data

                ));
            $context  = stream_context_create($options);
            $result = file_get_contents($url, FILE_TEXT, $context);

            $result_obj = json_decode($result);
            $result_arr = [
                'result' => $result_obj->result,
                'message' => $result_obj->message,
            ];
            return $result_arr;
            /* 返回结果示例
            成功
            {
                "message":"请求成功",
                "info":{"successCount":1,"smsIds":["1458113381893_15_3_11_1ainnq$131112345678"]}},
                "result":true,
                "statusCode":200
            }

            失败
            {
                "message":"手机号格式错误",
                "info":{},
                "result":false,
                "statusCode":412
            }
             */
        }else {
            echo 'no sms';
        }

    }

    /**
     * 安全过滤
     */
    public static function RemoveXSS($val) {
        $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);

        $search = 'abcdefghijklmnopqrstuvwxyz';
        $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $search .= '1234567890!@#$%^&*()';
        $search .= '~`";:?+/={}[]-_|\'\\';
        for ($i = 0; $i < strlen($search); $i++) {
            $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
            $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
        }

        $ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
        $ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
        $ra = array_merge($ra1, $ra2);

        $found = true;
        while ($found == true) {
            $val_before = $val;
            for ($i = 0; $i < sizeof($ra); $i++) {
                $pattern = '/';
                for ($j = 0; $j < strlen($ra[$i]); $j++) {
                    if ($j > 0) {
                        $pattern .= '(';
                        $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                        $pattern .= '|';
                        $pattern .= '|(&#0{0,8}([9|10|13]);)';
                        $pattern .= ')*';
                    }
                    $pattern .= $ra[$i][$j];
                }
                $pattern .= '/i';
                $replacement = substr($ra[$i], 0, 2).substr($ra[$i], 2); // add in <> to nerf the tag
                $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
                if ($val_before == $val) {
                    $found = false;
                }
            }
        }
        return trim(htmlspecialchars($val));
    }

}